/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.dataaccess.sqlserver;

import io.iec.edp.caf.commons.dataaccess.DbType;
import io.iec.edp.caf.commons.dataaccess.GSPDbConfigData;
import io.iec.edp.caf.data.source.Utils;

import java.text.MessageFormat;

/**
 * @author wangyandong
 * @date 2020/04/22 下午 01:54
 *
 */
public class SqlDbConfigData extends GSPDbConfigData {
    private static final String ConnFormat = "data source={0};initial catalog={1};user id={2};password={3};Connect Timeout={4};Pooling=True";
    private static final String ConnFormatWithPoolSize = "data source={0};initial catalog={1};user id={2};password={3};Connect Timeout={4};Pooling=True;Max Pool Size={5}";
    /// <summary>
    /// 构造函数。
    /// </summary>
    public SqlDbConfigData(){
        super();
        this.setDbType (DbType.SQLServer);
    }

    /// <summary>
    /// 数据库连接的配置字符串。
    /// </summary>
    @Override
    public String getConnectionString() {
        String result = null;
        String source = this.getSource();
        if (source != null && !"".equals(source)) {

            source = source.replace(':', ',');
            if (this.getMaxPoolSize() == 0)
                result = MessageFormat.format(ConnFormat, source, this.getCatalog(), this.getUserId(), this.getPassword(), this.getConnectTimeout());
            else
                result = MessageFormat.format(ConnFormatWithPoolSize, source, this.getCatalog(), this.getUserId(), this.getPassword(), this.getConnectTimeout(), this.getMaxPoolSize());
        }
        return result;
    }

    /// <summary>
    /// 加密后的数据库连接字符串。
    /// </summary>
    @Override
    public String getEncryptedConString() {
        String result = "";

        String source = this.getSource().replace(':', ',');

        if (this.getMaxPoolSize() == 0)
            result = MessageFormat.format(ConnFormat, Utils.encrypt(source), Utils.encrypt(this.getCatalog()),
                    Utils.encrypt(this.getUserId()), Utils.encrypt(this.getPassword()));
        else
            result = MessageFormat.format(ConnFormatWithPoolSize, Utils.encrypt(source), Utils.encrypt(this.getCatalog()),
                    Utils.encrypt(this.getUserId()), Utils.encrypt(this.getPassword()), this.getConnectTimeout(), this.getMaxPoolSize());

        return result;
    }
}
